<template>
  <div class="draft-notice-container">
    <!-- 查询表单 -->
    <div class="search-form">
      <el-form :model="formData" label-width="80px">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="员工工号">
              <el-input v-model="formData.empId" placeholder="请输入员工工号" clearable @keyup.enter="onQuery" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="员工姓名">
              <el-input v-model="formData.empName" placeholder="请输入员工姓名" clearable @keyup.enter="onQuery" />
            </el-form-item>
          </el-col>
          <el-col :span="12" style="text-align: right">
            <el-button type="primary" @click="onQuery">查询</el-button>
            <el-button @click="onReset">重置</el-button>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <!-- 员工表格 -->
    <div class="notice-table">
      <el-table :data="employees" border style="width: 100%" :row-style="{ height: '45px' }" v-loading="loading">
        <el-table-column prop="empId" label="员工ID" align="center" />
        <el-table-column prop="name" label="姓名" align="center" />
        <el-table-column prop="deptName" label="部门名称" align="center" />
        <el-table-column prop="positionName" label="职位名称" align="center" />
        <el-table-column prop="age" label="年龄" align="center" />
        <el-table-column label="上下级关系" align="center">
          <template #default="scope">
            <el-tag :type="scope.row.isLeader === 1 ? 'success' : 'primary'">
              {{ scope.row.isLeader === 1 ? '领导' : '员工' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" fixed="right">
          <template #default="scope">
            <el-button link type="primary" size="small" @click="editNode(scope.row)">修改</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页组件 -->
    <div class="pagination">
      <el-pagination :current-page="page.currentPage" :page-size="page.pageSize" :total="page.total"
        layout="total, prev, pager, next, jumper" @current-change="handlePageChange" />
    </div>

    <!-- 编辑对话框 -->
    <el-dialog v-model="showEditForm" title="员工调动" width="30%" :close-on-click-modal="false" align-center>
      <el-form :model="currentEmployee" label-width="100px">
        <el-form-item label="员工编号">
          <el-input v-model="currentEmployee.empId" disabled />
        </el-form-item>
        <el-form-item label="员工姓名">
          <el-input v-model="currentEmployee.name" disabled />
        </el-form-item>
        <el-form-item label="所属部门">
          <el-select v-model="currentEmployee.deptName" placeholder="请选择部门" style="width: 100%"
            @change="handleDeptChange">
            <el-option v-for="dept in departments" :key="dept.id" :label="dept.name" :value="dept.name" />
          </el-select>
        </el-form-item>
        <el-form-item label="职位名称">
          <el-select v-model="currentEmployee.positionName" placeholder="请选择职位" style="width: 100%">
            <el-option v-for="position in positions" :key="position.id" :label="position.name" :value="position.name" />
          </el-select>
        </el-form-item>
        <el-form-item label="上下级关系">
          <el-select v-model="currentEmployee.isLeader" placeholder="请选择关系" style="width: 100%">
            <el-option label="领导" :value="1" />
            <el-option label="员工" :value="0" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showEditForm = false">取消</el-button>
        <el-button type="primary" @click="confirmSubmit">确定</el-button>
      </template>
    </el-dialog>

    <!-- 确认对话框 -->
    <el-dialog v-model="showConfirmSubmitDialog" title="确认提交" width="30%" align-center>
      <p>确认将 <strong>{{ currentEmployee.name }}</strong> 调动到 "<strong>{{ currentEmployee.deptName }}</strong>" ，担任
        "<strong>{{
          currentEmployee.positionName }}</strong>" ，设置其上下级关系为 "<strong>{{ currentEmployee.isLeader === 1 ? '领导' : '员工'
          }}</strong>"
        ,并对该员工发送调动通知吗？</p>
      <template #footer>
        <el-button @click="showConfirmSubmitDialog = false">取消</el-button>
        <el-button type="primary" @click="submitEditForm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { getPositionList } from "../../api/basedata.js";
import { getAllDepts } from "../../api/dept.js";
import {
  getAllPositions,
  updateEmpPosition,
  getPositionsByDeptName,
} from "../../api/position.js";
import { addMessage } from "../../api/message.js";
import moment from "moment";
import { getSessionStorageObj } from "../../utils/common.js";
import { getAdminIdByAccount } from "../../api/admin.js";

export default {
  data() {
    return {
      formData: {
        empId: "",
        empName: "",
        pageNum: "",
        pageSize: "",
      },
      employees: [], // 员工数据
      departments: [], // 部门数据
      positions: [], // 职位数据
      currentEmployee: {
        empId: "",
        name: "",
        deptName: "", // 当前部门名称
        positionName: "", // 当前职位名称
        isLeader: "", // 当前上下级关系
        originalDeptName: "", // 修改前的部门名称
        originalPositionName: "", // 修改前的职位名称
        originalIsLeader: "", // 修改前的上下级关系
      }, // 当前选中的员工
      showEditForm: false, // 控制编辑表单的显示与隐藏
      showConfirmSubmitDialog: false, // 控制确认提交对话框的显示与隐藏
      page: {
        currentPage: 1,
        pageSize: 10,
        total: 0,
      },
      adminAccount: "",
      loading: false, // 控制加载状态
    };
  },
  methods: {
    // 查询方法
    onQuery() {
      this.page.currentPage = 1; // 查询时重置到第一页
      this.getList(); // 调用获取列表数据的方法
    },

    // 重置方法
    onReset() {
      this.formData = {
        empId: "",
        empName: "",
      };
    },

    // 分页变化处理
    handlePageChange(number) {
      this.formData.pageNum = number; // 更新当前页码
      this.page.currentPage = number;
      this.getList();
    },

    //API-获取分页数据
    getList() {
      this.formData.pageSize = this.page.pageSize;
      getPositionList(this.formData).then((res) => {
        console.log(res);
        this.employees = res.result.records;
        this.page.total = res.result.total;
        this.page.currentPage = res.result.current;
      });
    },

    // 处理部门选项变化
    handleDeptChange() {
      // 清空职位选项
      this.positions = [];
      // 清空当前员工的职位名称
      this.currentEmployee.positionName = "";
      // 加载新的职位选项
      this.loadPositionOptions();
    },

    // 点击修改按钮
    editNode(row) {
      this.showEditForm = true;
      // 复制当前行数据
      this.currentEmployee = {
        empId: row.empId,
        name: row.name,
        deptName: row.deptName,
        positionName: row.positionName,
        isLeader: row.isLeader,
        originalDeptName: row.deptName, // 记录修改前的部门名称
        originalPositionName: row.positionName, // 记录修改前的职位名称
        originalIsLeader: row.isLeader, // 记录修改前的上下级关系
      };
      this.loadPositionOptions(); // 加载职位选项
    },

    // 确认提交
    confirmSubmit() {
      // 确保部门和职位存在
      if (
        !this.currentEmployee.deptName ||
        !this.currentEmployee.positionName
      ) {
        this.$message.error("修改失败！请选择有效的部门和职位");
        return;
      }

      // 检查是否有修改
      const isModified =
        this.currentEmployee.deptName !==
        this.currentEmployee.originalDeptName ||
        this.currentEmployee.positionName !==
        this.currentEmployee.originalPositionName ||
        this.currentEmployee.isLeader !== this.currentEmployee.originalIsLeader;

      if (!isModified) {
        this.$message.info("未做任何修改");
        this.showEditForm = false;
        return;
      }
      this.positions = [];
      this.showConfirmSubmitDialog = true; // 显示确认提交对话框
    },

    // api-提交修改表单
    async submitEditForm() {
      // 调用API进行修改
      const params = {
        empId: this.currentEmployee.empId,
        deptName: this.currentEmployee.deptName,
        positionName: this.currentEmployee.positionName,
        isLeader: this.currentEmployee.isLeader,
      };

      try {
        const res = await updateEmpPosition(params);
        if (res.flag) {
          this.$message.success("修改成功");
          this.showEditForm = false;
          this.getList(); // 重新加载列表数据
          await this.getAdminId(); // 获取管理员ID
          this.sendMessage(); // 发送调动通知
        } else {
          this.$message.error(res.reason);
          this.showEditForm = false;
          this.getList(); // 重新加载列表数据
        }
      } catch (error) {
        console.error(error);
        this.$message.error("请求失败，请稍后重试");
      }
      this.showConfirmSubmitDialog = false; // 隐藏确认提交对话框
      //this.currentEmployee = {}; // 清空当前员工数据
    },

    // api-发送调动通知
    sendMessage() {
      console.log("发送调动通知");
      const params = {
        empId: this.currentEmployee.empId,
        content:
          `尊敬的${this.currentEmployee.name}:\n` +
          `\t您好!\n` +
          `\t经公司管理层研究决定现对您的工作岗位进行调整。具体调整如下:\n` +
          `\t您将被调至${this.currentEmployee.deptName}，担任${this.currentEmployee.positionName
          }一职，根据新的岗位安排，您的职位性质为${this.currentEmployee.isLeader === 1 ? "领导" : "员工"
          }。\n` +
          `\t请您在新的岗位上继续努力工作,展现出色的工作能力和团队合作精神。感谢您对公司的支持与配合！`,
        isRead: 0,
        sendTime: moment().format("YYYY-MM-DD HH:mm:ss"), // 格式化时间
        //adminId: this.$store.state.userInfo.id,
        adminId: this.adminId,
      };
      addMessage(params).then((res) => {
        if (res.flag) {
          this.$message.success("调动通知已发送");
        } else {
          this.$message.error("调动通知发送失败");
        }
      });
      this.currentEmployee = {}; // 清空当前员工数据
    },

    // 加载部门选项
    loadDepartmentOptions() {
      getAllDepts().then((res) => {
        if (res.flag) {
          this.departments = res.result;
          this.positions = [];
        }
      });
    },

    // 加载职位选项
    loadPositionOptions() {
      // 清空职位列表
      this.positions = [];
      // 获取当前选中的部门名称
      const selectedDeptName = this.currentEmployee.deptName;
      if (!selectedDeptName) {
        // 如果没有选中部门，清空职位列表
        this.positions = [];
        return;
      }

      // api-获取该部门下的职位名称列表
      getPositionsByDeptName({ deptName: selectedDeptName })
        .then((res) => {
          if (res.flag) {
            // 将返回的职位名称列表转换为 { id: name } 格式，以便 el-select 使用
            this.positions = res.result.map((positionName, index) => ({
              id: index + 1, // 使用简单的索引作为 id
              name: positionName,
            }));
          } else {
            this.$message.error(res.reason || "获取职位列表失败");
            this.positions = [];
          }
        })
        .catch((error) => {
          console.error(error);
          this.$message.error("请求失败，请稍后重试");
          this.positions = [];
        });
    },

    // api-获取管理员ID
    async getAdminId() {
      const params = {
        account: this.adminAccount // 显式绑定到当前实例
      };
      console.log(params);
      try {
        const res = await getAdminIdByAccount(params);
        console.log(res);
        if (res.flag) {
          this.adminId = res.result;
        } else {
          this.$message.error("获取管理员ID失败");
        }
      } catch (error) {
        console.error(error);
        this.$message.error("获取管理员ID失败");
      }
    },
  },
  mounted() {
    this.getList(); // 初始化加载数据
    this.loadDepartmentOptions(); // 加载部门数据
    this.positions = [];
    let adminInfo = getSessionStorageObj("adminInfo");
    this.adminAccount = adminInfo.account;
    //this.getAdminId(); 
    console.log(this.adminAccount);
  },
};
</script>

<style scoped>
.draft-notice-container {
  padding: 20px;
  height: 95%;
  display: flex;
  flex-direction: column;
}

.search-form {
  background: #fff;
  padding: 20px 20px 0 20px;
  margin-bottom: 20px;
  border-radius: 4px;
}

.notice-table {
  flex: 1;
  background: #fff;
  padding: 20px;
  border-radius: 4px;
  margin-bottom: 20px;
}

.pagination {
  text-align: right;
  background: #fff;
  padding: 10px 20px;
  border-radius: 4px;
}
</style>